package com.sphd.restaurantsystem.fragments.rec;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sphd.restaurantsystem.R;
import com.sphd.restaurantsystem.activitys.recorder.OrdersInfoActivity;
import com.sphd.restaurantsystem.adapters.StateAAdapter;
import com.sphd.restaurantsystem.base.LazyLoadFragment;
import com.sphd.restaurantsystem.base.RestaurantUrl;
import com.sphd.restaurantsystem.info.LoginInfo;
import com.sphd.restaurantsystem.info.RestaurantInfo;
import com.sphd.restaurantsystem.info.SalesInfo;
import com.sphd.restaurantsystem.interfaces.SatateValCallBack;
import com.sphd.restaurantsystem.presenter.StateAPresenterImpl;
import com.sphd.restaurantsystem.utils.Constant;
import com.sphd.restaurantsystem.view.StateAView;
import com.wzh.frame.utils.StringUtils;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Hu on 2016/12/9.
 */

public class StateFragment extends LazyLoadFragment implements SwipeRefreshLayout.OnRefreshListener, StateAView {

    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    private int curpage = 1;
    StateAAdapter stateAAdapter;
    StateAPresenterImpl stateAPresenter;
    SatateValCallBack satateValCallBack;
    RestaurantInfo restaurantInfo;
    LoginInfo loginInfo;
    SalesInfo item;
    int state;

    public void setCallBack(SatateValCallBack satateValCallBack, RestaurantInfo restaurantInfo, int i) {
        this.satateValCallBack = satateValCallBack;
        this.restaurantInfo = restaurantInfo;
        this.state = i;
    }

    @Override
    public int getLayout() {
        return R.layout.swf_and_recy;
    }

    @Override
    public void initViews(View view) {
        ButterKnife.bind(this, view);
        init();
        initEvent();
    }

    private void init() {
        loginInfo = DataSupport.findLast(LoginInfo.class);
        setRecy(myRecy);
        stateAPresenter = new StateAPresenterImpl(this);
        initAdapter();

    }

    private void initAdapter() {
        setRecy(myRecy);
        setRefresh(mySwf);
        stateAAdapter = new StateAAdapter(R.layout.item_fragment_statea, new ArrayList<>(), state);
        myRecy.setAdapter(stateAAdapter);
        stateAAdapter.openLoadAnimation();
        stateAAdapter.openLoadMore(10);
    }

    private void initEvent() {
        mySwf.setOnRefreshListener(this);
        stateAAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                curpage++;
                loadData();
            }
        });
        myRecy.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constant.SALESINFO, (SalesInfo) baseQuickAdapter.getItem(i));
                bundle.putSerializable(Constant.RESTAURANTSINFO, restaurantInfo);
                intent.putExtras(bundle);
                intent.setClass(context, OrdersInfoActivity.class);
                startActivityForResult(intent, 1);
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                int id = view.getId();
                switch (id) {
                    case R.id.receive_btn:
                        recOk((SalesInfo) adapter.getItem(position));
                        break;
                    case R.id.cancel_btn:
                        recCancle((SalesInfo) adapter.getItem(position));
                        break;
                }

            }
        });
    }


    private void recCancle(SalesInfo item) {
        if (isReciverCanDo(loginInfo, restaurantInfo)) {
            showCancelDialog(item);
        } else {
            toast("暂无权限。");
        }
    }

    /**
     * 取消订单的提示框
     *
     * @param
     */
    private void showCancelDialog(final SalesInfo salesInfo) {
        LayoutInflater li = LayoutInflater.from(context);
        View promptsView = li.inflate(R.layout.layout_edittextdialog, null);
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);

        // set prompts.xml to alertdialog builder
        alertDialogBuilder.setView(promptsView);
        alertDialogBuilder.setTitle("订单:" + salesInfo.getOrder_no()
                + "\n取消原因");
        final EditText userInput = (EditText) promptsView
                .findViewById(R.id.input);
        userInput.setHint("");
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // get user input and set it to result
                                // edit text
                                cancelOrdersNet(userInput.getText().toString(), salesInfo);

                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();

    }

    private void cancelOrdersNet(String cancerOrder, SalesInfo salesInfo) {
        stateAPresenter.sendCancleUrl(RestaurantUrl.Httptitle +
                RestaurantUrl.CancelSalesAndOrders + "remark=" + StringUtils.utf8Encode(cancerOrder) + "&orderno=" + salesInfo.getOrder_no());
    }

    private void recOk(SalesInfo item) {
        if (isReciverCanDo(loginInfo, restaurantInfo)) {
            if (item.getOrder_status() < 3) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("orderno", item.getOrder_no());
                map.put("cgid", String.valueOf(item.getOrder_cgid()));
                map.put("memPhone", item.getOrder_memphone());
                map.put("type", "" + item.getOrder_pay());
                map.put("realprice", String.valueOf(item.getOrder_lastprice() + item.getOrder_cardpay()));
                map.put("cgname", item.getOrder_cg());
                map.put("isgive", restaurantInfo.isCg_isgive() ? "1" : "0");
                map.put("ticket", String.valueOf(item.getOrder_ticket()));
                map.put("isyh", restaurantInfo.isCg_isyh() ? "1" : "0");
                if (!StringUtils.isEmpty(item.getOrder_memcard())) {
                    map.put("memcard", item.getOrder_memcard());
                }
                switch (item.getOrder_status()) {
                    case 0:
                        map.put("orderStatus", "1");
                        break;
                    case 1:
                        if (item.getOrder_isosale() == 1) {
                            map.put("orderStatus", "2");
                        } else {
                            map.put("orderStatus", "3");
                        }

                        break;
                    case 2:
                        map.put("orderStatus", "3");
                        break;
                    case 3:
                        break;

                    default:
                        break;
                }
                this.item = item;
                stateAPresenter.recUrl(RestaurantUrl.Httptitle + RestaurantUrl.ChangeStatus, map);

            }
        } else {
            toast("没有接单权限");
        }
    }

    @Override
    public void loadData() {
        stateAPresenter.addData(RestaurantUrl.Httptitle
                + RestaurantUrl.AllOrdersForType + "status=" + state + "&cgid=" + restaurantInfo.getId() + "&curpage=" + curpage + "&pageno=10");
    }

    @Override
    public void onRefresh() {
        curpage = 1;
        loadData();
    }

    @Override
    public void recResAndList(int status0sum, int status1sum, int status2sum, int status3sum, int status6sum, List<SalesInfo> salesInfos) {
        satateValCallBack.returnVal(status0sum, status1sum, status2sum, status3sum, status6sum);
        if (salesInfos.size() != 10) {
            stateAAdapter.loadComplete();
        }
        if (curpage == 1) {
            stateAAdapter.setNewData(salesInfos);
        } else {
            stateAAdapter.addData(salesInfos);
        }
        mySwf.setRefreshing(false);
    }

    @Override
    public void recRes(int res) {
        if (res == 1) {
            if (state == 0) {
                satateValCallBack.setCurrentItem(1);
            } else if (state == 1) {
                if (item.getOrder_isosale() == 1) {
                    satateValCallBack.setCurrentItem(2);
                } else {
                    satateValCallBack.setCurrentItem(3);
                }
            } else if (state == 2) {
                satateValCallBack.setCurrentItem(3);
            }
        } else {
            toast("提交失败，请重试！");
        }

    }

    @Override
    public void recCancleRes(int status) {
        if (status == 1) {
            if (state == 0) {
                satateValCallBack.setCurrentItem(4);
            }
        } else {
            toast("取消失败，请重试！");
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        onRefresh();
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
        mySwf.setRefreshing(false);
    }
}
